package com.ruoyi.system.service.connectUnity.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.controller.CxBase;
import com.ruoyi.system.domain.PrizeWinRecord;
import com.ruoyi.system.service.connectUnity.IConnectService;
import com.ruoyi.system.status.ConnectUrl;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ConnectServiceImpl extends CxBase implements IConnectService {

    private static final String QR_CODE_IMAGE_PATH = RuoYiConfig.getUploadPath()+"/QRcode";

    public JSONObject doPostJson(JSONObject json,String url){
        //此处将要发送的数据转换为json格式字符串
        //String jsonText = "{\"appid\":\"" + "029DA96A87AE23E8" + "\",\"secret\":\""+HttpUtils.PQuserInfo(username)+ "\",\"username\":\"" + username +"\"}";//HttpUtils.PQuserInfo(username)
        //String jsonText = "{\"appid\":\"" + "029DA96A87AE23E8" + "\",\"secret\":\""+HttpUtils.PQuserInfo(username)+ "\",\"username\":\"" + username+ "\",\"password\":\"" + HttpUtils.PQpassword(password) +"\"}";
        //JSONObject json = (JSONObject) JSONObject.parse(jsonText);
        String jsonText = ConnectUrl.ndkyedu;
        JSONObject sr = this.doPost(json,jsonText,url);
        return sr;
    }

    public JSONObject doGetJson(String url){
        //此处将要发送的数据转换为json格式字符串
        String jsonText = ConnectUrl.ndkyedu+url;
        JSONObject json = new JSONObject();
        JSONObject sr = this.doGet(jsonText);
        return sr;
    }

    // 可逆的加密算法
    public String encryption(String inStr) {
        // String s = new String(inStr);
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    // 加密后解密
    public String decrypt(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }

    public String PQcreate(PrizeWinRecord prizeWinRecord) {
        try {
            return "https://ga.ndky.edu.cn:8081"+ Constants.RESOURCE_PREFIX+generateQRCodeImage(encryption(prizeWinRecord.toJasonString()), 350, 350,RuoYiConfig.getUploadPath()+"/QRcode/"+prizeWinRecord.getPrizeWinDate()+prizeWinRecord.getStudentId()+".png");
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }
        return null;
    }
    /**
     * 统信用户信息加密
     *统信接口需要加密
     */
    public String PQuserInfo(String userid)
    {
        String dateStr=new SimpleDateFormat("yyyyMMdd").format(new Date());
        String appsecret=ConnectUrl.appsecret;
        String username = userid;
        //32位 大写
        String encryptedvalue = DigestUtils.md5DigestAsHex((username+appsecret+dateStr).getBytes());
        return encryptedvalue.toUpperCase();
    }
    /**
     * 统信密码加密
     *统信接口需要加密
     */
    public String PQpassword(String password)
    {
        String e1=getBase64(password);
        String appid=ConnectUrl.appid;
        String e2=getBase64(e1+appid);
        return e2;
    }


    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    public static JSONObject doGet(String url) {
        HttpClient client = HttpClients.createDefault();
        client = (CloseableHttpClient)wrapClient(client);
        // 要调用的接口方法
        HttpGet get = new HttpGet(url);
        JSONObject jsonObject = null;
        try {
            HttpResponse res = client.execute(get);
            String result = EntityUtils.toString(res.getEntity());// 返回json格式：
            jsonObject = JSONObject.parseObject(result);
            jsonObject.getJSONObject("content");
            jsonObject.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject.getJSONObject("content");
    }

    public static JSONObject doPost(JSONObject date,String username,String url) {
        HttpClient client = HttpClients.createDefault();
        client = (CloseableHttpClient)wrapClient(client);
        // 要调用的接口方法
        url = ConnectUrl.ndkyedu+url;
        HttpPost post = new HttpPost(url);
        post.setHeader(new BasicHeader("Accept","application/json;charset=UTF-8"));
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(date.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "application/json");
            HttpResponse res = client.execute(post);
            //if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(res.getEntity());// 返回json格式：
            jsonObject = JSONObject.parseObject(result);
            //}
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject.getJSONObject("content");
    }


    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {
                }
                public void checkServerTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpClients.createDefault();
        }
    }

    private static String generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        int dirLastIndex = RuoYiConfig.getProfile().length();
        String currentDir = StringUtils.substring(filePath, dirLastIndex);
        BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        return currentDir;
    }

}
